from rest_framework import serializers
from . import models

class FileSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.File
        fields = ['id', 'md5','mimetype','filename','size']

class FileUploadByMD5Serializer(serializers.Serializer):
    user_id = serializers.IntegerField(write_only=True) # 关联用户的主键
    filename = serializers.CharField(max_length=150) #  文件名
    def create(self, value):
        local_file = self.context['local_file'] # 单独传入处理 一个数据对象
        file = models.File.objects.create(
            storage = local_file.storage,
            size = local_file.size,
            md5 = local_file.md5,
            mimetype = local_file.mimetype,
            type = local_file.type,
            addr = local_file.addr,
            **value,
        )
        return file
